package c_04;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author fu-xiao-liu
 * @Date 2022/6/7 18:54
 */
public class Load7 {
    public static void main(String[] args) throws Exception  {
        //6. 使用者调用该类加载器的 loadClass 方法
        MyClassLoader classLoader = new MyClassLoader();
        Class<?> c1 = classLoader.loadClass("MapImpl1");
        Class<?> c2 = classLoader.loadClass("MapImpl1");
        System.out.println(c1 == c2);

        MyClassLoader classLoader2 = new MyClassLoader();
        Class<?> c3 = classLoader2.loadClass("MapImpl1");
        System.out.println(c1 == c3);

        c1.newInstance();
    }
}
/**
 * @date  自定义类加载器
 * 1. 继承 ClassLoader 父类
 */
class MyClassLoader extends ClassLoader {
    /**
     * 2. 要遵从双亲委派机制，重写 findClass 方法（不是重写 loadClass方法，否则不会走双亲委派机制）
     */
    @Override
    public Class<?> findClass(String name) throws ClassNotFoundException {
        //3.确定加载路径
        String path = "D:\\StudyJava\\AboutDiKnown\\study-08-JVM\\target\\classes\\" + name +".class";
        try {
            //4. 读取类文件的字节码
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            Files.copy(Paths.get(path),os);
            //5.字节码文件转二进制数组
            byte[] bytes = os.toByteArray();
            //6. 调用父类的 defineClass 方法来加载类
            return defineClass(name, bytes, 0, bytes.length);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ClassNotFoundException("类文件未找到", e);
        }
    }
}
